package com.oa.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.joneying.common.redis.RedisManager;
import com.oa.core.exception.DataIsEmptyException;
import com.oa.core.utils.FastJsonSerializerUtil;
import com.oa.system.entity.User;
import com.oa.system.entity.UserInfo;
import com.oa.system.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Controller基类
 * Created by wangfan on 2018-02-22 上午 11:29.
 */

public class BaseController {

    @Value("${server.domain}")
    public String domain;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    private RedisManager redisManager;


    public String getCookie(String key) {
        Cookie[] cookies = request.getCookies();

        String value = "";

        if(cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    value = cookie.getValue();
                }
            }
        }
        return value;
    }

    /**
     * 获取当前登录的user
     */
//    public UserInfo getLoginUser() {
//
//        Authentication authentication = SecurityContextHolder.getContext ().getAuthentication ();
//        if (authentication != null) {
//            Object object = authentication.getPrincipal ();
//            if (object != null) {
//                return FastJsonSerializerUtil.toObject(JSON.toJSONString(object), UserInfo.class);
//            }
//        }
//        return null;
//    }

    /**
     * 获取当前登录的userId
     */
    public String getLoginUserId() {
        Object obj = redisManager.get(getCookie("ticket"));
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(obj, userVO);
        return userVO == null ? null : userVO.getId();
    }

}
